<?php namespace Home\Controller; 

use Hdphp\Controller\Controller;
use Home\Model\Reg;

class RegController extends Controller
{
	protected $db;
	
	public function __init()
	{
		$this->db = new Reg;
	}
   	// 首页调用
    public function reg(){
       View::make();
    }

    //调用验证码
    public function code()
    {
    	Code::make();
    }

    //数据插入数据库
    public function add()
    {
    	if (IS_POST)
    	{
    		// 邮件正则
    		// $preg = "/^([0-9A-Za-z\\-_\\.]+)@([0-9a-z]+\\.[a-z]{2,3}(\\.[a-z]{2})?)$/i";
    		// 判断邮箱地址最终格式是否正确
    		// if(!preg_match_all($preg, $_POST["username"]))
    		// {
    		// 	View::error("邮件格式不正确");
    		// 	return false;
    		// }
    		//判断邮箱邮箱是否已经注册
    		$username = $this->db->only($_POST['username']);
    		if($_POST['username'] == $username['username'])
    		{
    			View::error('该邮箱已经注册');
    			return false;
    		}
    		// 判断两次密码是否真确
    		if($_POST['password'] != $_POST['password_c'])
    		{
    			View::error("两次密码不正确");
    			return false;
    		}
    		// 判断验证码是否正确
    		if(strtoupper($_POST['code']) != $_SESSION['code'])
    		{
    			View::error("验证码不正确");
    			return false;
    		}
    		// 设置新数组变量
    		$data['username'] = $_POST['username'];
    		$data['nickname'] = $_POST['username'];
    		$data['email'] = $_POST['username'];
    		$data['password'] = md5($_POST['password']);
    		$data['regtime'] = time();
    		// 插入数据库
    		if($this->db->store($data))
    		{
    			$_SESSION['id'] = $username['id'];
    			$_SESSION['username'] = $username['username'];
    			$_SESSION['nickname'] = $username['nickname'];
    			// 成功后跳转首页
    			View::success('恭喜你注册成功',U('Index/index'));
    		}
    	}
    }
}
